define(['jquery', 'bootstrap', 'utilback', 'table', 'form', 'selectpage'], function ($, undefined, Utilback, Table, Form) {

    var Controller = {
    	config: {
    		get_url: '/building/read/detail',
    	},
        init: function () {
            // 初始化表格参数配置
            Table.api.init({
            	singleSelect: true,
                extend: {
                    index_url: '/building/read/page',
                    add_url: 'buildingEdit.html',
                    edit_url: 'buildingEdit.html',
                    del_url: '/building',
                    multi_url: '/building',
                }
            });

            var table = $("#table");

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                columns: [
                    [
                        {field: 'state', checkbox: true, },
                        {field: 'id', title: 'ID'},
                        {field: 'areaName', title: __('所属区域')},
                        {field: 'buildingName', title: __('楼栋名')},
                        {field: 'managerName', title: __('楼栋管家')},
                        {field: 'managerPhone', title: __('楼栋管家联系方式')},
                        {field: 'elevatorNum', title: __('楼栋电梯数')},
                        {field: 'equipmentNum', title: __('楼栋消防设备数')},
                        {field: 'totalHouse', title: __('房屋数')},
                        {field: 'manageFee', title: '物业费(元/月/平方)'},
                        {field: 'operate', title: __('Operate'), events: Table.api.events.operate, formatter: function (value, row, index) {
                             return Table.api.formatter.operate.call(this, value, row, index, table);
                        }}
                    ]
                ]
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
        },
        edit: function () {
            Form.api.bindevent($("form[role=form]"));
            Util.api.initSelectOption({
    			url: '/area/read/list',
            	target: '[name="areaId"]',
            	param: { orderBy: 'area_name', sortAsc: 'Y' },
            	codeText: 'areaName',
    		    code : 'id',
            	init: function() {
                    var id = Util.api.query('id');
                	if(id) {
                		$('.ben-house').remove();
        	        	Form.api.fill($('form'), Controller.config.get_url, id, function(data) {
        	        		$('[name="managerId"]').attr('data-init', data.managerId);
        	        		initManagerId();
        	        		$('[name="areaId"]').selectpicker('val', data.areaId);
        	        		if(data.totalUnit) $('[name="totalUnit"]').change();
        	        	});
                	} else {
                		initManagerId();
                	}
                	
		        	function initManagerId() {
	            		$('[name="managerId"]').selectPage({
	            			data: '/user/read/page',
	            			showField: 'userName',
	            		    keyField : 'id',
	            		    searchField: 'keyword',
	            			eAjaxSuccess: function(data) {
	            				return {
	            					"pageSize": data.size,
	            		            "pageNumber": data.current,
	            		            "totalRow": data.total,
	            		            "totalPage": data.pages,
	            		            "list": data.rows
	            				};
	            			}
	            		});
		        	}
            	}
            });
            
            var unit = 0;
            $('#addUnit').on('click', function() {
            	var u = $(this).removeClass('active').clone().attr('id', '');
            	unit++;
            	u.addClass('unitName').attr('data-id', unit);
            	u.find('a').attr('href', '#unit' + unit).text(unit+'单元');
            	$(this).before(u);
            	var c = $($(this).find('a').attr('href')).removeClass('active');
            	c.find('.houses').html('');
            	var nc = c.clone().attr('id', 'unit' + unit);
            	nc.find('[type="text"]').val('');
            	nc.find('.ben-house').attr('data-id', unit);
            	c.before(nc);
            	setTimeout(function() {
                	$('[href="#unit'+unit+'"]').trigger('click');
            	}, 50);
            });
            $('[name="totalUnit"]').on('change', function() {
            	var totalUnit = $(this).val();
            	for(var i=0;i<totalUnit-unit;i++) {
            		setTimeout(function() {
            			$('#addUnit').trigger('click');
                	}, 50);
            	}
            });

            $(document).on('click', '.unitName .close-tab', function() {
            	var L = $(this).parent();
            	if(L.attr('data-id') == unit) {
                	L.prev().find('a').trigger('click');
                	$(L.find('a').attr('href')).remove();
                	L.remove();
                	unit--;
                	if(unit == 0) {
                		$('#addUnit').addClass('active');
                		$('#unit').addClass('active');
                	}
            	}
            });
            
            // 生成房屋编号
            $(document).on('click', '.ben-house', function() {
            	var html = '';
            	var totalFloor = $('[name="totalFloor"]').val();
            	var floorHourse = $(this).parent().find('[name="floorHourse"]').val();
            	for(var i=1; i <= totalFloor; i++) {
            		html += '<div class="form-group col-xs-10">';
            		for(var j=1; j <= floorHourse; j++) {
                		html += '<div class="col-xs-4"><div class="input-group"><input type="text" name="houseNos" value="'
                		 + (unit == 0 ? '' : $(this).attr('data-id') + '-') + (i + '0' + j)
                		 +'" class="form-control" placeholder="请输入房屋号">'
                		 +'<span class="btn-google input-group-addon btn-delHouse"><i class="fa fa-remove"></i></span>'
                         +'</div></div>';
                	}
            		html += '</div>';
            	}
            	$(this).parent().find('.houses').html(html);
            });
            
            $(document).on('click', '.btn-delHouse', function() {
            	$(this).parent().parent().remove();
            });
        }
    };
    return Controller;
});